package com.nanbei.stack;

import java.util.Iterator;

/**
 * @ClassDescription: 数组实现栈操作
 * @JdkVersion: 17
 * @Author: BaoShan.li
 * @Created: 2023/11/24 16:16
 */
public class ArrayStack<E> implements StackInterface<E>,Iterable<E>{


    private final E[] array;
    private final int capacity;
    private int top = 0;

    @SuppressWarnings("all")
    public ArrayStack(int capacity) {
        this.array = (E[]) new Object[capacity+1];
        this.capacity = capacity;
    }

    @Override
    public boolean push(E value) {
        if (isFull()){
            return false;
        }
        array[top++] =value;
        return true;
    }

    @Override
    public E pop() {
        if (isEmpty()){
            return null;
        }
        return array[--top];
    }

    @Override
    public E peek() {
        if (isEmpty()){
            return null;
        }
        return array[top -1];
    }

    @Override
    public boolean isEmpty() {
        return top == 0;
    }

    @Override
    public boolean isFull() {
        return top == capacity;
    }

    @Override
    public Iterator<E> iterator() {
        return new Iterator<E>() {
            int p = top -1;
            @Override
            public boolean hasNext() {
                return p >= 0;
            }

            @Override
            public E next() {
                E e = array[p];
                p--;
                return e;
            }
        };
    }
}
